package com.web.controller.api;

import com.google.common.collect.Maps;
import com.web.config.SmsConfig;
import com.web.domain.Dict;
import com.web.domain.Response;
import com.web.dto.SmsDto;
import com.web.manager.AliSmsManager;
import com.web.utils.AESCipher;
import com.web.utils.MathUtil;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author FDjavaone
 * @date 2017/8/30
 */
@RestController
@RequestMapping("api")
public class SmsController {

    @Autowired
    private SmsConfig smsConfig;
    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;

    /**product传验证码*/
    @RequestMapping("/open/sms/validation")
    public Response validation(SmsDto smsDto) throws Exception {
        String vcode=stringRedisTemplate.opsForValue().get(Dict.Constants.REDIS_NAMESPACE_PHONE+"1000:"+smsDto.getMobile());
        if(vcode==null){
            return Response.failure("验证码已失效");
        }
        if(!smsDto.getProduct().equals(vcode)) {
            return Response.failure("验证码不正确");
        }
        stringRedisTemplate.delete(Dict.Constants.REDIS_NAMESPACE_PHONE+"1000:"+smsDto.getMobile());
        return Response.ok("验证码验证一致");
    }

    /**
     * 发送手机验证码
     *
     */
    @ResponseBody
    @RequestMapping(value = "/open/sms/sendCode",method = RequestMethod.POST)
    public Response sendCode(SmsDto smsDto) throws Exception{
        String result= AESCipher.aesDecryptString(new String(Base64.decodeBase64(smsDto.getSecret()),"utf-8"), "msksystemsms0830");
        Date date=new Date();
        String spl="-";
        if(Math.abs(new Long(result.split(spl)[2])-date.getTime())/(1000 * 60)> 1){
            return Response.failure("时间异常！");
        }else {

        }
        String phone=result.split("-")[0];

        String method="1000";
        Response response =null;
        //1分钟内不可重发发送短信
        if(AliSmsManager.cache.getIfPresent(Dict.Constants.REDIS_NAMESPACE_PHONE+phone)!=null){
            return Response.custom().failure("短信发送频繁,请稍后...");
        }
        //生产六位随机数
        String vcode = MathUtil.getSix();
        //短信模板不存在
        if(!smsConfig.getTemplate().containsKey(method)){
            return Response.custom().failure(900111,"mehtod-templcate illegal");
        }
        String templateParam="{\"code\":\""+vcode+"\"}";
        Response sendRes=send(phone,smsConfig.getTemplate().get(method),templateParam,"");
        if (sendRes.isOk()) {
            //保存发送记录到缓存中3分钟
            stringRedisTemplate.opsForValue().set(Dict.Constants.REDIS_NAMESPACE_PHONE+method+":"+phone,vcode,3, TimeUnit.MINUTES);
            //保存到本地缓存中，默认1分钟
            AliSmsManager.cache.put(Dict.Constants.REDIS_NAMESPACE_PHONE+phone,vcode);
            response=Response.builder().status(Response.SUCCESS).message("验证码发送成功！").data(Maps.newHashMap()).build();
            ((Map)response.getData()).put("phone", phone);

        } else {
            response=Response.builder().status(900002).message("验证码发送失败！"+sendRes.getMessage()).build();
        }
        return response;
    }
    public Response send(String phoneNumbers,String templateCode,String templateParam,String outId){
        String  accessKeyId=smsConfig.getSms().getAccessKeyId();
        String  accessKeySecret=smsConfig.getSms().getAccessKeySecret();
        String  regionId=smsConfig.getSms().getRegionId();
        String  signName=smsConfig.getSms().getSignName();
        AliSmsManager.SmsDto smsDto= AliSmsManager.SmsDto.builder().accessKeyId(accessKeyId).
                accessKeySecret(accessKeySecret).regionId(regionId).phoneNumbers(phoneNumbers).
                templateCode(templateCode).signName(signName).templateParam(templateParam).outId(outId).build();
        return AliSmsManager.sendSms(smsDto);
    }
}
